package com.example.area.io.netty.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * @author kancy
 * @date 2019/2/23 14:34
 */
@Slf4j
public class Client {
	private static final int DEFAULT_SERVER_PORT = 7777;
	private static final String DEFAULT_HOST = "127.0.0.1";

	public static void main(String[] args) {
		start();
	}

	public static void start() {
		Socket socket = null;
		PrintWriter pw = null;
		BufferedReader br = null;
		try {
			socket = new Socket(DEFAULT_HOST, DEFAULT_SERVER_PORT);
			pw = new PrintWriter(socket.getOutputStream(),true);
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String line = null;
			while(true){

				// 发送数据
				System.out.println("请输入数据：");
				Scanner sc  = new Scanner(System.in);
				line = sc.next();
				pw.println(line);
				if("bye".equals(line)){
					break;
				}

				//等待数据返回
				line = br.readLine();
				log.info("服务端返回数据：" + line);
				if("bye".equals(line)){
					break;
				}
			}


		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeResource(br,pw);
			closeSocket(socket);
		}
	}

	private static void closeSocket(Socket socket) {
		if(socket != null){
			try {
				if(!socket.isClosed()){
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		log.info("关闭连接!");
		socket = null; // help gc
	}

	private static void closeResource(Reader in, Writer out) {
		try {
			if (in != null){
				in.close();
				in = null; // help gc
			}
			if (out != null){
				out.close();
				out = null; // help gc
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
